import { useEffect, useMemo, useRef, useState } from 'react';
import { Button, Space, Form, Row, Col, Input, Spin, Popover, Card, Select, Empty } from 'antd';
import { queryStubMonitorList, StubMonitor } from './services'
import { useRequest } from 'ahooks';
import { Access, styled, history } from '@umijs/max'
import { CheckOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { queryStationListForSelectOption } from '../stationList/services';
import { GunStatusColorMap, GunStatus } from '../stubList/services';
import { jump2target } from '@/utils/common';

const StubRow = styled.div`
  width: 100%;
  display: flex;

  .checked, .unchecked {
    .badge {
      width: 34px;
      height: 20px;
      position: absolute;
      right: -12px;
      bottom: -6px;
      transform: rotate(-45deg);
    }

    .check {
      position: absolute;
      color: #fff;
      font-size: 12px;
      right: 1px;
      bottom: -2px;
    }
  }

  .checked {
    border: 1px solid var(--ant-color-primary);

    .badge {
      background-color: var(--ant-color-primary);
    }
  }

  .unchecked {
    border: 1px solid #eeeeee;

    .badge {
      background-color: #eeeeee;
    }
  }

  .item {
    width: 120px;
    height: 80px;
    padding: 0 24px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    cursor: pointer;
    position: relative;
    border-radius: 6px;
    overflow: hidden;

    .header {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #888888;

      .extra {
        color: orange;
        cursor: pointer;
      }
    }

    .value {
      font-size: 28px;
      line-height: 28px;
      font-weight: bold;
    }
  }

  .kw {
    border: 0;
    width: 160px;
    min-width: 120px;
    padding: 0;
    cursor: unset;
  }
`

const Statistics = styled.div`
  width: 0;
  flex-grow: 1;
  min-height: 280px;
  padding: 12px 12px 44px;
  position: relative;
  border-right: 1px solid #f0f0f0;

  .footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    height: 32px;
    border-top: 1px solid #f0f0f0;
    padding: 8px 0;
    display: flex;

    .item {
      width: 50%;
      height: 100%;
      border-right: 1px solid #f0f0f0;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
  }

  .status {
    font-size: 20px;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;

    .sort {
      width: 28px;
      height: 28px;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 16px;
      font-weight: bold;
    }
  }

  .item {
    width: 100%;
    height: 28px;
    display: flex;
    align-items: center;
    font-size: 14px;

    .label {
      color: #888888;
      width: 88px;
      flex-shrink: 0;

      &::after {
        content: ':';
      }
    }

    .value {
      flex: 1;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
`

const StationSelect = styled.div`
  .ant-select-selection-item {
    font-size: 24px;
    font-weight: bold;
  }
`

type StubItem = {
  title: string
  explain?: string
  value: number
  status: string
}

type FilterParams = {
  equipmentId?: string
  stubId?: string
  status?: string
}

const AppUserPage: React.FC<RoutePageProps> = (props) => {
  const [searchForm] = Form.useForm()
  const stubItems = useRef<StubItem[]>([
    {title: '全部', status: 'all', value: 0},
    {title: '故障', status: GunStatus.故障, value: 0},
    {title: '离线', status: GunStatus.离线, value: 0},
    {title: '占用', explain: '充电后插枪占位', status: GunStatus.充电后占位, value: 0},
    {title: '充电中', status: GunStatus.充电中, value: 0},
    {title: '空闲', status: GunStatus.空闲, value: 0},
    {title: '其他', status: GunStatus.其他, value: 0},
  ])
  const list = useRequest(queryStubMonitorList, {manual: true, pollingInterval: 1000 * 15, onSuccess: (_data) => {
    const { stubNum } = _data.data
    stubItems.current[1].value = stubNum.acErrorNum + stubNum.dcErrorNum
    stubItems.current[2].value = stubNum.acOffLineNum + stubNum.dcOffLineNum
    stubItems.current[3].value = stubNum.acOccupyNum + stubNum.dcOccupyNum
    stubItems.current[4].value = stubNum.acChargeNum + stubNum.dcChargeNum
    stubItems.current[5].value = stubNum.acFreeNum + stubNum.dcFreeNum
    stubItems.current[6].value = stubNum.acOtherNum + stubNum.dcOtherNum
    stubItems.current[0].value = stubNum.acNum + stubNum.dcNum
  }})
  const [stationId, setStationId] = useState<string>()
  const stationList = useRequest(queryStationListForSelectOption)
  const [filterParams, setFilterParams] = useState<FilterParams>({
    status: 'all'
  })

  const onStationChange = (id: string) => {
    setStationId(id)
    list.run({stubGroupId: id})
  }

  const onStubStatusChange = (status: string) => {
    setFilterParams({
      ...filterParams,
      status,
    })
  }

  const onFinish = (formValues: any) => {
    setFilterParams({
      ...filterParams,
      ...formValues,
    })
  }

  const renderStatusText = (status: GunStatus) => {
    switch (status) {
      case GunStatus.充电中: return '充电中'
      case GunStatus.其他: return '其他'
      case GunStatus.充电后占位: return '占用'
      case GunStatus.故障: return '故障'
      case GunStatus.离线: return '离线'
      case GunStatus.空闲: return '空闲'
      case GunStatus.插枪空闲: return '插枪空闲'
      default: return '其他'
    }
  }

  const jump2chargeOrder = (record: StubMonitor) => {
    sessionStorage.setItem('__chargingOrderOfStationWatch', JSON.stringify({
      stationId,
      stationName: stationList.data?.data.find(item => item.id === stationId)?.name,
      stubId: record.id,
    }))
    jump2target(`/order/chargeOrder?sKey=__chargingOrderOfStationWatch___${new Date().getTime()}`, {needRefresh: true})
  }

  const jump2stubLog = (record: StubMonitor) => {
    jump2target(`/station/stubLog?stubId=${record.id}`, {needRefresh: true})
  }

  const stubList = useMemo(() => {
    const result: Record<string, StubMonitor[]> = {};
    (list.data?.data.list || []).forEach((item: StubMonitor) => {
      const { equipmentId, stubId, status } = filterParams
      if (equipmentId && !item.id.includes(equipmentId)) return
      if (stubId && !item.id.includes(stubId)) return
      if (status && status !== 'all') {
        if (status === GunStatus.空闲) {
          if (![GunStatus.空闲, GunStatus.插枪空闲].includes(item.status)) return
        } else if (status === GunStatus.其他) {
          if ([
            GunStatus.充电中, GunStatus.充电后占位, GunStatus.插枪空闲,
            GunStatus.故障, GunStatus.离线, GunStatus.空闲,
          ].includes(item.status)) {
            return
          }
        } else if (item.status !== status) return
      }
      if (item.id.length === 9) { // 交流
        result[item.id] = [item]
      } else {
        const _key = item.equipmentId
        if (result[_key]) {
          result[_key].push(item)
        } else {
          result[_key] = [item]
        }
      }
    })
    return Object.values(result)
  }, [list.data, filterParams])

  useEffect(() => {
    if (props.params.id) {
      setStationId(props.params.id)
      list.run({stubGroupId: props.params.id})
    }
  }, [props.params.id])
  
  return (
    <div className='container'>
      <StationSelect>
        <Select
          options={stationList.data?.data.map(item => ({
            label: item.name,
            value: item.id,
          }))}
          allowClear={false}
          value={stationId}
          onChange={val => onStationChange(val)}
          variant='borderless'
          popupMatchSelectWidth={500}
          showSearch
          optionFilterProp='label'
        />
      </StationSelect>
      <div className="card">
        <Spin spinning={list.loading}>
          <StubRow>
            <div className="item kw">
              <div className="header">额定功率</div>
              <div className="value">
                <Space>
                  <span>{list.data?.data.stubNum.kw || 0}</span>
                  <span style={{fontSize: 14, color: '#888888'}}>kW</span>
                </Space>
              </div>
            </div>
            <div className="item kw" style={{borderRight: '1px solid #eeeeee', marginRight: 32}}>
              <div className="header">实时功率</div>
              <div className="value">
                <Space>
                  <span>{list.data?.data.stubNum.realKw || 0}</span>
                  <span style={{fontSize: 14, color: '#888888'}}>kW</span>
                </Space>
              </div>
            </div>
            <Space size={16}>
            {
              stubItems.current.map(item => (
                <div
                  className={`item ${item.status === filterParams.status ? 'checked' : 'unchecked'}`}
                  style={{padding: '12px 24px'}} key={item.title}
                  onClick={() => onStubStatusChange(item.status)}
                >
                  <div className="badge"></div>
                  <div className="check"><CheckOutlined /></div>
                  <div className="header">
                    <Space>
                      <span>{item.title}</span>
                      <Access accessible={!!item.explain}>
                        <Popover content={item.explain}>
                          <QuestionCircleOutlined />
                        </Popover>
                      </Access>
                    </Space>
                  </div>
                  <div className="value">{item.value}</div>
                </div>
              ))
            }
            </Space>
          </StubRow>
        </Spin>
      </div>
      <div className="card search-card">
        <div className="form-area">
          <Form
            name='searchWatchForm' form={searchForm} onFinish={onFinish}
          >
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='桩编号' name='equipmentId'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='枪编号' name='stubId'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <div className="header">电站监控</div>
        <Spin spinning={list.loading}>
          <Row gutter={[16, 16]}>
            {
              stubList.length > 0 ? stubList.map(item => {
                return <Col span={4 * item.length} key={item[0].id}>
                  <Card
                    title={<Popover content={item[0].equipmentId} placement='topLeft'>
                      <div>桩编号: {item[0].equipmentId}</div>
                    </Popover>}
                    styles={{
                      body: {padding: 0, display: 'flex'}
                    }}
                  >
                    {
                      item.map((_item, index) => (
                        <Statistics key={_item.id} style={index === 1 ? {borderRight: 0} : {}}>
                          <div className='status'>
                            <div className="sort" style={{
                              backgroundColor: _item.status ? GunStatusColorMap[_item.status] || GunStatusColorMap[GunStatus.其他] : GunStatusColorMap[GunStatus.其他]
                            }}>{`0${index+1}`}</div>
                            <span>{renderStatusText(_item.status)}</span>
                          </div>
                          <div className='item'>
                            <Popover content={_item.id} placement='topLeft'>
                              <div className="value" style={{fontWeight: 500, color: GunStatusColorMap[_item.status] || '#222222'}}>
                                <span>充电桩 {_item.id}</span>
                              </div>
                            </Popover>
                          </div>
                          <div className="item">
                            <div className="label">{[GunStatus.充电中, GunStatus.充电后占位].includes(_item.status as GunStatus) ? '车牌号' : '上次车牌号'}</div>
                            <div className="value">{_item.carPlat || '-'}</div>
                          </div>
                          <Access accessible={_item.status === GunStatus.充电中}>
                            <div className="item">
                              <div className="label">需求功率</div>
                              <div className="value">{_item.carKw ? `${_item.carKw}kw` : '-'}</div>
                            </div>
                          </Access>
                          <Access accessible={_item.status !== GunStatus.充电后占位}>
                            <div className="item">
                              <div className="label">实时功率</div>
                              <div className="value">{_item.kw ? `${_item.kw}kw` : '-'}</div>
                            </div>
                          </Access>
                          <Access accessible={_item.status === GunStatus.充电中}>
                            <div className="item">
                              <div className="label">充电量</div>
                              <div className="value">{_item.power ? `${_item.power}度` : '-'}</div>
                            </div>
                          </Access>
                          <Access accessible={_item.status !== GunStatus.充电中}>
                            <div className="item">
                              <div className="label">上次SOC</div>
                              <div className="value">{_item.soc || '-'}</div>
                            </div>
                          </Access>
                          <Access accessible={_item.status === GunStatus.充电后占位}>
                            <div className="item">
                              <div className="label">占用时长</div>
                              <div className="value">{_item.occupyTime ? `${_item.occupyTime}分钟` : '-'}</div>
                            </div>
                          </Access>
                          <Access accessible={_item.status === GunStatus.充电后占位}>
                            <div className="item">
                              <div className="label">停止原因</div>
                              <div className="value">{_item.endName || '-'}</div>
                            </div>
                          </Access>
                          <div className="footer">
                            <div className="item" onClick={() => jump2chargeOrder(_item)}>充电订单</div>
                            <div className="item" onClick={() => jump2stubLog(_item)} style={{borderRight: 0}}>状态日志</div>
                          </div>
                        </Statistics>
                      ))
                    }
                  </Card>
                </Col>
              }) : <div style={{width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '48px 0'}}>
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              </div>
            }
          </Row>
        </Spin>
      </div>
    </div>
  );
};

export default AppUserPage;
